package com.hliushi.netty.client;


import com.hliushi.netty.message.*;
import com.hliushi.netty.protocol.MessageCodecSharable;
import com.hliushi.netty.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();

        /**
         *
         */
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);

        AtomicBoolean LOGIN = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast(new ProtocolFrameDecoder());
                    // ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(new IdleStateHandler(0, 5, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        /**
                         * userEventTriggered 用来触发特殊事件
                         */
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug("5s 没有写数据了, 发送了一个心跳包");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {

                        /**
                         * 接收响应消息
                         */
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage responseMessage = (LoginResponseMessage) msg;
                                log.debug("{}", responseMessage);

                                if (responseMessage.isSuccess()) {
                                    // 登录成功
                                    LOGIN.set(true);
                                }
                                // 唤醒 system in 线程
                                WAIT_FOR_LOGIN.countDown();
                            }
                        }

                        /**
                         * 在连接建立后触发 active 事件
                         */
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 负责接收用户在控制台的输入, 负责向服务器发送各种消息
                            new Thread(() -> {
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户:");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();

                                LoginRequestMessage message = new LoginRequestMessage(username, password);
                                /**
                                 * ctx.writeAndFlush(message);
                                 * ctx.channel().writeAndFlush(message);
                                 * 都是触发出站处理器的执行
                                 * ctx.channel().write(msg) 从尾部开始查找出站处理器
                                 * ctx.write(msg) 是从当前结点找上一个出站处理器
                                 */
                                ctx.writeAndFlush(message);
                                // ctx.channel().writeAndFlush(message);
                                System.out.println("等待后续操作...");
                                try {
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                // 如果登录失败
                                if (!LOGIN.get()) {
                                    // --> close完成之后会通知ChannelFuture, channel.closeFuture().sync() 方法同步等待channel关闭
                                    ctx.channel().close();
                                    return;
                                }

                                boolean jumpLoopFlag = false;
                                while (!jumpLoopFlag) {

                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");        // 考虑下content存在空格的情况
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");
                                    String command = scanner.nextLine();
                                    if (command == null || "".equals(command)) {
                                        System.out.println("命令不能为空!");
                                        continue;
                                    }
                                    String[] s = command.split(" ");
                                    switch (s[0]) {
                                        case "send":
                                            // ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                            ctx.writeAndFlush(new ChatRequestMessage(username, s[1],
                                                    command.substring(s[0].length() + s[1].length() + 2)));
                                            break;
                                        case "gsend":
                                            // ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1],
                                                    command.substring(s[0].length() + s[1].length() + 2)));
                                            break;
                                        case "gcreate":
                                            HashSet<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                            set.add(username);      // 加入自己
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin":
                                            // 注意, 这种加入群聊, 是当前用户自己加入某个群, 而不是被别人邀请加入
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                                            break;
                                        case "quit":
                                            jumpLoopFlag = true;
                                            ctx.channel().close();
                                            break;
                                    }
                                }
                            }, "System in").start();
                            // super.channelActive(ctx);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 10010).sync().channel();
            channel.closeFuture().sync();   // 同步等待channel关闭, 可以在后面处理一些channel关闭善后工作
        } catch (Exception e) {
            log.error("server error: {}", e.getMessage(), e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
